package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.api.feign.system.dto.SysUserDTO;
import com.meteor.convert.PublicityConvert;
import com.meteor.entity.Publicity;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.PublicityMapper;
import com.meteor.query.PublicityQuery;
import com.meteor.service.PublicityService;
import com.meteor.vo.PublicityVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lynn
 * @date 2024/1/22
 */
@Service
@AllArgsConstructor
public class PublicityServiceImpl extends BaseServiceImpl<PublicityMapper, Publicity> implements PublicityService {


    private final PublicityMapper publicityMapper;

    private final SystemFeign systemFeign;

    @Override
    public void save(PublicityVO vo) {

        Publicity  entity= PublicityConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getMerchantId())){
                entity.setMerchantId(SecurityUser.getUser().getMerchantId());
            }

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
        }else{

            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }


        baseMapper.insert(entity);

    }

    @Override
    public void update(PublicityVO publicityVO) {

        Publicity publicity = PublicityConvert.INSTANCE.convert(publicityVO);
        if (ObjectUtils.isEmpty(publicity.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(publicity);

    }

    @Override
    public PublicityVO getPublicity(String id) {
        PublicityVO publicityVO = new PublicityVO();
        publicityVO = PublicityConvert.INSTANCE.convert(baseMapper.selectById(id));
        ResponseData responseData = JSON.parseObject(systemFeign.getUser(publicityVO.getCreatedBy()),ResponseData.class);
        if(!ObjectUtils.isEmpty(responseData.getData())){
            SysUserDTO sysUserDTO = JSON.parseObject(responseData.getData().toString(),SysUserDTO.class);
            publicityVO.setCreatedName(sysUserDTO.getRealName());
        }
        return publicityVO;
    }

    @Override
    public List<PublicityVO> getPublicityVOList(PublicityQuery publicityQuery) {

        List<Publicity> publicities = baseMapper.selectList(getWrapper(publicityQuery));

        return PublicityConvert.INSTANCE.convertList(publicities);
    }

    @Override
    public PageResult<PublicityVO> pagePublicityVO(PublicityQuery query) {

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<Publicity> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<PublicityVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());

//        IPage<Publicity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

//        return new PageResult<PublicityVO>(PublicityConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private Map<String, Object> getParams(PublicityQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("title", query.getTitle());
        params.put("content", query.getContent());
        params.put("type", query.getType());
        params.put("orgId", query.getOrgId());
        params.put("merchantId", query.getMerchantId());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_publicity"));

        return params;
    }

    private Map<String, Object> getNoAuthParams(PublicityQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("title", query.getTitle());
        params.put("content", query.getContent());
        params.put("type", query.getType());
        params.put("orgId", query.getOrgId());
        params.put("merchantId", query.getMerchantId());
        params.put("publicType", query.getPublicType());
        params.put("communityId",query.getCommunityId());

        return params;
    }


    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public PageResult<PublicityVO> miniPage(PublicityQuery query) {
        // 查询参数
        Map<String, Object> params = getNoAuthParams(query);

        if(!ObjectUtils.isEmpty(query.getPublicType())&&query.getPublicType() == 1){
            query.setLimit(3);
        }
        // 分页查询
        IPage<Publicity> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<PublicityVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());
    }


    private Wrapper<Publicity> getWrapper(PublicityQuery query){
        LambdaQueryWrapper<Publicity> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getTitle()), Publicity::getTitle, query.getTitle());
        wrapper.like(StrUtil.isNotBlank(query.getContent()), Publicity::getContent, query.getContent());
        wrapper.eq(query.getType() != null, Publicity::getType, query.getType());
        wrapper.eq(StrUtil.isNotBlank(query.getMerchantId()), Publicity::getMerchantId, query.getMerchantId());
        wrapper.eq(StrUtil.isNotBlank(query.getOrgId()), Publicity::getOrgId, query.getOrgId());

        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }
}
